<template>
	<view class="page_content header-bg">
		<!-- <view class=""></view> -->
		<view class="head_content">
			<CustomNavbar title="Phone verification" rightText="Complete" @rightClick="rightClick">
			</CustomNavbar>
			<view class="content items">
				<view class="cell">
					<u-input placeholder="Enter new phone number" border="none" v-model="form.phone">
							<country-code-selector slot="prefix" :countryCode.sync="nation"></country-code-selector>
					</u-input>
				</view>
				<view class="cell">
					<u-input placeholder="Please enter verification code" border="none" v-model="form.code">
						<u--text :text="isSendCode?`Resend in ${codeTime} seconds`:'Get verification code'" slot="suffix" type="tips" @click="sendCode"></u--text>
					</u-input>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import countryCodeSelector from '../../components/vue-country-code-selector/index.vue'
	import CustomNavbarHome from '../../components/CustomNavbar-home.vue'
	export default {
		components: { CustomNavbarHome, countryCodeSelector },
		data() {
			return {
				nation: 66,
				form: {
					phone: '',
					code: ''
				},
				isSendCode: false,
				codeTime: 60
			}
		},
		onLoad(op) {
		},
		methods: {
			replace(str, val) {
				return str.replace('X', val)
			},
			rightClick() {
				let { token, uid } = this.$store.state.user
				let { phone, code } = this.form
				if(!phone) {
					uni.$u.toast('Enter new phone number')
					return 
				}
				if (phone && code) {
					this.$request('user.update', { id: uid, phone }).then(res => {
						uni.navigateBack({ delta: 1 })
					})
				}
			},
			sendCode() {
				let { phone } = this.form
				let obj = {
					nation: this.nation,
					phone
				}
				this.$request('login.sendCode', obj, false)
					.then(res => {
						uni.hideLoading()
						uni.$u.toast('Verification code sent')
						this.isSendCode = true
						let timer = setInterval(() => {
							if(this.codeTime <= 0) {
								this.isSendCode = false
								clearInterval(timer)
								return
							}
							this.codeTime--
						}, 1000)
					})
					.catch(err => {
						uni.hideLoading()
						uni.$u.toast('Failed to send verification code！')
					})
			}
		}
	}
</script>

<style>
	.content {
		width: 688rpx;
		margin: 0 auto;
		margin-top: 34rpx;
		color: white;
	}

	.items {
		background: rgba(255, 255, 255, .1);
		border-radius: 23rpx;
	}

	.items .cell {
		height: 92rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0 32rpx;
		position: relative;
		overflow: hidden;
	}

	.items .cell:first-child::after {
		content: " ";
		position: absolute;
		background-color: rgb(218, 218, 218, 0.4);
		bottom: 0;
		height: 1rpx;
		width: 90%;
	}
</style>